<?php

/**
 * CelebrioPeople Person
 *
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    CelebrioPeople
 */
namespace ApplicationsModule\PeopleModule;

use \Nette\Object;
use \Nette\String;
use \dibi;


use Celebrio\Core\IModuleInit;
use Celebrio\Core\DummyInit;
use Celebrio\Core\ServiceProvider;
use Celebrio\Core\DDL;
use \Celebrio\Core\NoSuchServiceException;

use \Celebrio\AccessControl\UserManagement;

use Celebrio\Modules;

/**
 * People module initialization (db scripts).
 * 
 * @author pavel
 */
class PeopleInit extends DummyInit implements IModuleInit {
    
    private static $avatarLocation = "avatar.png";
    //todo input it dynamicaly during the ppl app setup

    public function init(array $configuration) {
        parent::init($configuration);

        UserManagement::$creation_hooks[] = array(
            "class" => PeopleManagement::getReflection()->name,
            "requires" => array(),
            "provides" => array("base"),
            "method" => "createPerson"
        );

    }

    public function install(array $configuration) {
        parent::install($configuration);

        // save avatar to VFS
        $data = file_get_contents(__DIR__ . "/" . self::$avatarLocation);
        $fs = ServiceProvider::getService(Modules::FS);
        $fs->save(PeopleManagement::AVATAR, $data);

        // create records in the people table for already existing users
        $this->peopleFromUsers();
    }

    public function uninstall() {
        parent::uninstall();

        // delete people module information from users table
        dibi::update("users", array("id_person" => null))->execute();
    }

    public function peopleFromUsers() {

        $pm = new PeopleManagement();
        
        $user_rows = dibi::select(array("id", "first_name", "last_name", "user_name"))
                ->from("users")
                ->where(array("id_person" => null))
                ->fetchAll();

        foreach ($user_rows as $user) {
            if (empty($user->last_name)) {
                $user->last_name = String::capitalize($user->user_name);
            }
            $person = new Person($user->first_name, $user->last_name);
            $person->setUserId($user->id);
            $pm->createPerson($person); // includes connecting to the user
        }

    }

}